package com.yjha.huazhubusiness.utils;

// import com.alibaba.druid.util.StringUtils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
// import com.yjha.lzmarathonsys.value.GeneralCode;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yjha.huazhubusiness.value.GeneralCode;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtils {
    //private static Logger log = LoggerFactory.getLogger(JwtUtils.class);

    public static final Long TOKEN_TIME = 80000L;

    /** token秘钥，请勿泄露，请勿随便修改  */
    public static final String SECRET = GeneralCode.TOKEN_SECRET;
    /** token 过期时间: 10天 */
    /*public static final int calendarField = Calendar.DATE;
    public static final int calendarInterval = GeneralCode.TOKEN_OUT_OF_DATE;*/

    /**
     * JWT生成Token.<br/>
     *
     * JWT构成: header, payload, signature
     *
     * @param user_id
     *            登录成功后用户user_id, 参数user_id不可传空
     */
    public static String createToken(Long user_id) throws Exception {
        //log.info("create token...");
        // expire time
        /*Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();*/
        Date start = new Date();                        //h
        long currentTime = System.currentTimeMillis() + 60 * 60 *1000;//一小时有效时间
        Date end = new Date(currentTime);
        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        // build token
        // param backups {iss:Service, aud:APP}
        String token = JWT.create().withHeader(map) // header
                .withClaim("iss", "Service") // payload
                .withClaim("aud", "APP").withClaim("user_id", null == user_id ? null : user_id.toString())
                .withIssuedAt(start) // sign time
                .withExpiresAt(end) // expire time
                .sign(Algorithm.HMAC256(SECRET)); // signature
        return token;
    }


    /**
     * 解密Token
     *
     * @param token
     * @return
     * @throws Exception
     */

    public static Map<String, Claim> verifyToken(String token) throws Exception{
        DecodedJWT jwt = null;
        //log.info("start identify token...");
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        jwt = verifier.verify(token);
        return jwt.getClaims();

    }

    /**
     * 根据Token获取user_id
     *
     * @param token
     * @return user_id
     */

    public static Long getUID(String token) throws Exception{
        Map<String, Claim> claims = verifyToken(token);
        Claim user_id_claim = claims.get("user_id");
        if (null == user_id_claim || StringUtils.isEmpty(user_id_claim.asString())) {
            return 0L;
        }
        //log.info("get userid " + Long.valueOf(user_id_claim.asString()));
        return Long.valueOf(user_id_claim.asString());
    }

    public static String getTokenFromRequest(HttpServletRequest request) {
        // 1. 优先从 Cookie 获取
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }

        // 2. 从 Authorization Header 获取
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }

        return null;
    }


    public static String getToken(Map<String,Object> map){
        JWTCreator.Builder builder = JWT.create();
        // payload
        map.forEach((k, v) -> {
            if (v instanceof String) {
                builder.withClaim(k, (String) v); // 如果是 String，直接添加
            } else if (v instanceof Integer) {
                builder.withClaim(k, String.valueOf(v)); // 如果是 Integer，转换为 String 添加
            } else {
                // 处理其他类型，根据需要决定是否抛出异常或忽略
                throw new IllegalArgumentException("Unsupported value type for key: " + k + ", value: " + v);
            }
        });

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);       //过期时间
//        instance.add(Calendar.MINUTE,1);       //过期时间

        builder.withExpiresAt(instance.getTime());
        String token = builder.sign(Algorithm.HMAC256(SECRET));

        return token;
    }
    /**
     * 根据Token获取user_id
     *
     * @param token
     * @return user_id
     */

    public static String getOpenId(String token){
       try {
           Map<String, Claim> claims = verifyToken(token);
           Claim user_id_claim = claims.get("openid");
           if (null == user_id_claim || StringUtils.isEmpty(user_id_claim.asString())) {
               return null;
           }
           //log.info("get userid " + Long.valueOf(user_id_claim.asString()));
           return String.valueOf(user_id_claim.asString());
       }catch (Exception e){
           return null;
       }
    }
}
